from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area


class ProvinceAreasView(View):
    def get(self,request):
        """
        提供省数据
        :param request:
        :return:
        """
        province_list = cache.get('province_list')
        if not province_list:
            try:
                # province_model_list = Area.objects.filter(parent_isnull=True)
                province_model_list = Area.objects.filter(parent__isnull=True)
                province_list = []
                for province_model in province_model_list:
                    dict = {'id':province_model.id,
                            'name':province_model.name}
                    province_list.append(dict)
                cache.set('province_list',province_list,3600)

            except Exception as e :
                return JsonResponse({
                    'code':400,
                    'errmsg':'省份数据错误'
                })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'province_list':province_list
        })


class SubAreasView(View):
    def get(self,request,pk):
        """
        市区信息获取
        :param request:
        :return:
        """
        data_dict = cache.get('data_dict_%s' % pk)
        if not data_dict:
            try:
                # 市区
                sub_model_list = Area.objects.filter(parent=pk)
                # 省
                parent_model = Area.objects.get(id=pk)
                sub_list = []
                for sub_model in sub_model_list:
                    sub_dict = {
                        'id':sub_model.id,
                        'name':sub_model.name
                    }
                    sub_list.append(sub_dict)
                data_dict = {
                    'id': parent_model.id,
                    'name': parent_model.name,
                    'subs': sub_list
                }
                cache.set('data_dict_%s' % pk,data_dict,3600)
            except Exception as e:
                return JsonResponse({
                    'code':400,
                    'errmsg':'读取区县失败'
                })
        return JsonResponse({
            'code':0,
            'errmsg':'ok',
            'sub_data':data_dict
        })
